

/*
 * @(#)ListFormReportSummaryAction.java
 *
 * Copyright (c) 2003 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */
package com.dcivision.form.web;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jxl.Workbook;
import jxl.format.Alignment;
import jxl.write.NumberFormats;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableWorkbook;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.dcivision.form.bean.FormElement;
import com.dcivision.form.bean.FormElementType;
import com.dcivision.form.bean.FormPage;
import com.dcivision.form.bean.FormRecord;
import com.dcivision.form.bean.FormSection;
import com.dcivision.form.dao.FormDataElementDAObject;
import com.dcivision.form.dao.FormElementDAObject;
import com.dcivision.form.dao.FormPageDAObject;
import com.dcivision.form.dao.FormRecordDAObject;
import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.ErrorConstant;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.SystemFunctionConstant;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.Utility;
import com.dcivision.framework.web.AbstractActionForm;
import com.dcivision.framework.web.AbstractMaintAction;


/**
  ListFormReportSummaryAction.java

  This class is for list form report summary

    @author          Tony Chen
    @company         DCIVision Limited
    @creation date   16/01/2003
    @version         $Revision: 1.17.2.3 $
*/

public class ListFormReportSummaryAction extends AbstractMaintAction {

  public static final String REVISION = "$Revision: 1.17.2.3 $";

  protected String listName = "";
  private Integer formPageID = null;

  public ListFormReportSummaryAction() {
    super();
  }

  /**
   * getMajorDAOClassName
   *
   * @return  The class name of the major DAObject will be used in this action.
   */
  
  public String getMajorDAOClassName() {
    return("com.dcivision.form.dao.FormSubmissionDAObject");
  }

  /**
   * getFunctionCode
   *
   * @return  The corresponding system function code of action.
   */
  
  public String getFunctionCode() {
    return(SystemFunctionConstant.FORM_REPORT);
  }

  /**
   * setPageTitle
   * set the extend page title and page path.
   * default page path/title will be created by navmode and functionCode
   */
  
  public void setPageTitle(HttpServletRequest request, HttpServletResponse response, ActionForm form, ActionMapping mapping, ActionForward actionForward){
    FormRecord formRecord = (FormRecord)request.getAttribute("formRecord");
    if(!Utility.isEmpty(formRecord)){
      String extendTitle = formRecord.getTitle();
      StringBuffer extendPath = new StringBuffer();
      extendPath.append("<a href=\"ListFormReport.do?formGroupID="+request.getSession().getAttribute("formGroupID"));
      extendPath.append("&opMode="+GlobalConstant.OP_MODE_LIST_RETAIN+"\">");
      extendPath.append(formRecord.getGroupName());
      extendPath.append("</a>");
      request.setAttribute(GlobalConstant.EXTEND_PAGE_PATH, extendPath.toString());
      request.setAttribute(GlobalConstant.EXTEND_PAGE_TITLE, extendTitle);
      request.setAttribute(GlobalConstant.EXTEND_PAGE_TITLE_SHOW_ONLY, new Boolean(true));
    }
  }

  
  public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws ServletException {
    ActionForward forward = this.retrieveFunctionCode(request, response, mapping);
    if (forward!=null) {
      return forward;
    }

    int formPageNo = 0; // formPageNo is formPageList SeqNO,not formPage.getPageNo .
    String formRecordID = request.getParameter("formRecordID");
    if(!Utility.isEmpty(request.getParameter("formPageNo"))){
    	formPageNo = Integer.parseInt(request.getParameter("formPageNo"));
    }

    FormPageDAObject formPageDAO = new FormPageDAObject(this.getSessionContainer(request), this.getConnection(request));
    List formPageList = formPageDAO.getDetailListByFormRecordID(new Integer(formRecordID));

    FormPage tempFormPage = (FormPage)formPageList.get(formPageNo);
    formPageID = tempFormPage.getID();

    //  Set Page Title
    FormRecordDAObject formRecordDAO = new FormRecordDAObject(this.getSessionContainer(request),this.getConnection(request));
    FormRecord formRecord = (FormRecord)formRecordDAO.getByFormRecordID(formRecordID);
    request.setAttribute("formRecord", formRecord);

    selectRecord(mapping, (AbstractActionForm) form, request, response);
    if (FormRecord.EXPORT_EXCEL_FILE.equals(request.getParameter("operationType"))){
      expToExcel(request,response,form);
      return null;
    }
    return super.execute(mapping, form, request, response);
  }

  
  public void selectRecord(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
    try {
      MaintFormSubmissionForm formSubmissionForm = (MaintFormSubmissionForm)form;

      int pageNo = 0;

    	 if(!Utility.isEmpty(request.getParameter("formPageNo")) && !"null".equals(request.getParameter("formPageNo")) ){
    	   pageNo = Integer.parseInt(request.getParameter("formPageNo"));
    	 }

      Integer formRecordID = TextUtility.parseIntegerObj(formSubmissionForm.getFormRecordID());
      FormPageDAObject formPageDAO = new FormPageDAObject(this.getSessionContainer(request), this.getConnection(request));
      FormPage formPage = null;
      List formPageList = formPageDAO.getDetailListByFormRecordID(formRecordID);
      if (!Utility.isEmpty(formPageList) ){
      	 formPage = (FormPage)formPageList.get(pageNo);
        request.setAttribute("formPageList", formPage);
      }

      request.setAttribute("formPageListName",formPageList);

    } catch (ApplicationException appEx) {
      throw appEx;
    } catch (Exception e) {
      log.error(e, e);
      throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, e);
    } finally {}
  }

  public void expToExcel(HttpServletRequest request,HttpServletResponse response, ActionForm form){
    try{

     // response.setContentType("APPLICATION/OCTET-STREAM");
      response.addHeader("Content-Transfer-Encoding", "base64");
      String filename = "FormReport.xls";
      response.addHeader("Content-Disposition", "attachment; filename=" + filename + "\"");
      WritableFont titleFont = new WritableFont(WritableFont.ARIAL, 20, WritableFont.BOLD);
      WritableFont headerFont = new WritableFont(WritableFont.ARIAL, 10);
      WritableFont bodyFont = new WritableFont(WritableFont.ARIAL, 10);
      WritableFont footerFont = new WritableFont(WritableFont.ARIAL, 10, WritableFont.BOLD);
      WritableCellFormat titleCellFormat = new WritableCellFormat(titleFont);
      titleCellFormat.setAlignment(Alignment.RIGHT);
      WritableCellFormat headerCellFormat = new WritableCellFormat(headerFont);
      WritableCellFormat bodyCellFormat = new WritableCellFormat(bodyFont);
      WritableCellFormat numberCellFormat = new WritableCellFormat(bodyFont,NumberFormats.FLOAT);
      WritableCellFormat integerCellFormat = new WritableCellFormat(bodyFont,NumberFormats.INTEGER);
      WritableCellFormat footerCellFormat = new WritableCellFormat(footerFont);
      FormElementDAObject formElementDAO = new FormElementDAObject(this.getSessionContainer(request),this.getConnection(request));
      jxl.write.Label    slabel;
      ServletOutputStream sos =response.getOutputStream();
      WritableWorkbook xslwork=Workbook.createWorkbook(sos);


      int rowSpaceNuber=3;
      int iCol = -1;
      int pageListSize =0;
      Integer pageID = new Integer(0);
      Integer sectionID = new Integer(0);
      List formPageList = (List)request.getAttribute("formPageListName");

      if (request.getAttribute("formPageListName")!=null) {
        pageListSize = formPageList.size();
      }
      AbstractActionForm maintFormSubmissionForm = (MaintFormSubmissionForm)form;
      for (int n=0 ;n<pageListSize; n++){
        FormPage formPage = (FormPage) formPageList.get(n);
        pageID = formPage.getID();
        List formSectionList = formPage.getFormSectionList();
        jxl.write.WritableSheet ws=xslwork.createSheet("FormPage"+(n+1),n);
        slabel=new jxl.write.Label(3,1,formPage.getTitle());
        ws.addCell(slabel);
        iCol = -1;
        for (int i=0; i<formSectionList.size(); i++) {
          FormSection tmpFormSection = (FormSection) formSectionList.get(i);
          sectionID = tmpFormSection.getID();
          if (i==0){
            slabel=new jxl.write.Label(0,rowSpaceNuber,tmpFormSection.getTitle());
            ws.addCell(slabel);
          }else{
            slabel=new jxl.write.Label(iCol+1,rowSpaceNuber,tmpFormSection.getTitle());
            ws.addCell(slabel);
          }

          FormDataElementDAObject tmpFormDataElementDAO = new FormDataElementDAObject(this.getSessionContainer(request),this.getConnection(request));
          List formElementFormDataList = new ArrayList();
          int iRow = -1;
          try{
            formElementFormDataList = tmpFormDataElementDAO.getFormElementFormDataByPageIDSectionID(pageID,sectionID,maintFormSubmissionForm);
          } catch (ApplicationException appEx) {
          }
          String tmpFieldID = "";
          iRow = rowSpaceNuber+1;
          for (int ii=0; ii<formElementFormDataList.size(); ii++){
          	Object[] objFormElementFormData = null;
          	objFormElementFormData = (Object[])formElementFormDataList.get(ii);
            // falcon_add_start
            Integer elementID = new Integer(objFormElementFormData[2].toString());
            FormElement formElement = (FormElement)formElementDAO.getObjectByID(elementID);
            if(FormElementType.ELEMENT_PASSWORD.equals(formElement.getElementType())){
               objFormElementFormData[5] = "********************";
            }
            // falcon_add_end
          	if(tmpFieldID.equals(objFormElementFormData[2].toString()) ){
          		iRow ++;
          		if (!Utility.isEmpty(objFormElementFormData[6]) && FormElement.VALIDATION_INTEGER_ONLY.equals(objFormElementFormData[6]) ){
          			jxl.write.Number integer = new jxl.write.Number(iCol,iRow,Float.parseFloat(objFormElementFormData[5].toString()),integerCellFormat);
          			ws.addCell(integer);
          		}else if (!Utility.isEmpty(objFormElementFormData[6]) && FormElement.VALIDATION_NUMERIC_ONLY.equals(objFormElementFormData[6]) ){
          			jxl.write.Number number = new jxl.write.Number(iCol,iRow,Float.parseFloat(objFormElementFormData[5].toString()),numberCellFormat);
          			ws.addCell(number);
          		}else{
          			slabel=new jxl.write.Label(iCol,iRow,Utility.isEmpty(objFormElementFormData[5])?"":objFormElementFormData[5].toString());
          			ws.addCell(slabel);
          		}
          	} else {
          		iCol ++;
          		iRow = rowSpaceNuber+1;
          		slabel=new jxl.write.Label(iCol,iRow,objFormElementFormData[4].toString());
          		ws.addCell(slabel);
          		iRow ++;
          		if (!Utility.isEmpty(objFormElementFormData[6]) && FormElement.VALIDATION_INTEGER_ONLY.equals(objFormElementFormData[6]) ){
          			jxl.write.Number integer = new jxl.write.Number(iCol,iRow,Float.parseFloat(objFormElementFormData[5].toString()),integerCellFormat);
          			ws.addCell(integer);
          		}else if (!Utility.isEmpty(objFormElementFormData[6]) && FormElement.VALIDATION_NUMERIC_ONLY.equals(objFormElementFormData[6]) ){
          			jxl.write.Number number = new jxl.write.Number(iCol,iRow,Float.parseFloat(objFormElementFormData[5].toString()),numberCellFormat);
          			ws.addCell(number);
          		}else{
          			slabel=new jxl.write.Label(iCol,iRow,Utility.isEmpty(objFormElementFormData[5])?"":objFormElementFormData[5].toString());
          			ws.addCell(slabel);
          		}
          		tmpFieldID = Utility.isEmpty(objFormElementFormData[2])?"":objFormElementFormData[2].toString();
          	}

          }
        }
      }

      xslwork.write();
      xslwork.close();
      sos.close();
    } catch(Exception e){
       log.error(e, e);
    }
  }




}
